package com.ibeeking.found.msg.rest.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaSubscribeService;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.hutool.core.util.ObjectUtil;

import com.ibeeking.found.common.enums.msg.MsgTemplateTypeEnum;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.msg.rest.service.IMsgBindConfigService;
import com.ibeeking.found.msg.rest.service.IWxMaMsgTemplateService;
import com.ibeeking.found.msg.rest.service.IOpenService;
import com.ibeeking.found.msg.service.common.dos.WxMaMsgTemplateDO;
import com.ibeeking.found.msg.service.common.query.WxMaMsgTemplateQuery;
import com.ibeeking.found.msg.service.common.vo.MsgBindConfigVO;
import com.ibeeking.found.msg.service.common.vo.WxMaMsgTemplateVO;
import com.ibeeking.found.msg.service.mapper.WxMaMsgTemplateMapper;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.bean.subscribemsg.TemplateInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description:
 * @Author ibeeking
 * @Date 2022/1/7 11:17
 **/
@Service
public class WxMaMsgTemplateServiceImpl implements IWxMaMsgTemplateService {
    @Resource
    private WxMaMsgTemplateMapper wxMaMsgTemplateMapper;

    @Resource
    private IMsgBindConfigService msgBindConfigServiceImpl;

    @Resource
    private IOpenService wxOpenServiceImpl;

    @SneakyThrows
    @Override
    public Integer syncWxMaMsgTemplateListFromWx() {
        Long tenantId = UserUtils.getTenantID();
        WxMaService wxMaService = wxOpenServiceImpl.getWxOpenMaService(tenantId);
        if (wxMaService == null) {
            throw new BusinessException("无法获取小程序信息，请检查是否绑定小程序！");
        }
        WxMaConfig WxMaConfig = wxMaService.getWxMaConfig();
        if (WxMaConfig == null) {
            throw new BusinessException("无法获取小程序信息，请检查是否绑定小程序！");
        }
        String appId = WxMaConfig.getAppid();
        WxMaSubscribeService wxMaSubscribeService = wxMaService.getSubscribeService();
        if (wxMaSubscribeService == null) {
            throw new BusinessException("无法获取小程序信息，请检查是否绑定小程序！");
        }
        List<TemplateInfo> templateList = wxMaSubscribeService.getTemplateList();

        if(StringUtils.isEmpty(appId)){
            throw new BusinessException("无法获取小程序APPID，请检查是否绑定小程序！");
        }
        if (Collections3.isEmpty(templateList)) {
            wxMaMsgTemplateMapper.delete(null);
        } else {
            wxMaMsgTemplateMapper.delete(null);
            List<WxMaMsgTemplateDO> wxMaMsgTemplateDOS = JsonUtils.jsonToList(templateList, WxMaMsgTemplateDO.class);
            wxMaMsgTemplateDOS.stream().forEach(d->{
                d.setAppId(appId);
                d.setCreateTime(LocalDateTime.now());
                d.setModifyTime(LocalDateTime.now());
            });
            wxMaMsgTemplateMapper.insertBatchSomeColumn(wxMaMsgTemplateDOS);
        }
        return templateList.size();
    }


    @Override
    public List<WxMaMsgTemplateVO> list(WxMaMsgTemplateQuery query) {
        List<WxMaMsgTemplateDO> templateDOS = wxMaMsgTemplateMapper.selectList(new LambdaQueryWrapper<WxMaMsgTemplateDO>()
                .eq(query.getId() != null , WxMaMsgTemplateDO::getId, query.getId())
                .eq(StringUtils.isNotEmpty(query.getTemplateCode()), WxMaMsgTemplateDO::getPriTmplId, query.getTemplateCode())
                .eq(StringUtils.isNotEmpty(query.getTemplateName()), WxMaMsgTemplateDO::getTitle, query.getTemplateName())
         );
        //todo 临时增加同步模板消息
        //if (Collections3.isEmpty(templateDOS)) {
        //    getBean().syncWxMaMsgTemplateListFromWx();
        //}
        List<WxMaMsgTemplateVO> templateVOS = JsonUtils.jsonToList(templateDOS, WxMaMsgTemplateVO.class);
        return templateVOS;
    }

    @Override
    public Boolean del(Long id) {
        WxMaMsgTemplateDO wxMaMsgTemplateDO = wxMaMsgTemplateMapper.selectById(id);
        if (wxMaMsgTemplateDO == null) throw new BusinessException("数据不存在");
        String templateCode = wxMaMsgTemplateDO.getPriTmplId();
        if(StringUtils.isNotEmpty(templateCode)){
            List<MsgBindConfigVO> msgBindConfigVOS = msgBindConfigServiceImpl.listByTemplateType(MsgTemplateTypeEnum.MSG_TEMPLATE_WX_MA_SUBSCRIP.getCode(),templateCode);
            if(msgBindConfigVOS != null && msgBindConfigVOS.size() >0){
                throw new BusinessException("消息已经绑定，请先解绑后再删除");
            }
        }
        return wxMaMsgTemplateMapper.deleteById(id) >0;
    }

    /**
     * 查询小程序订阅消息模板
     *
     * @param code
     * @return
     */
    @Override
    public WxMaMsgTemplateVO queryTemplateByCode(String code) {
        LambdaQueryWrapper<WxMaMsgTemplateDO> templateQueryWrapper = Wrappers.lambdaQuery(WxMaMsgTemplateDO.class);
        templateQueryWrapper.eq(WxMaMsgTemplateDO::getPriTmplId, code);
        WxMaMsgTemplateDO templateDo = wxMaMsgTemplateMapper.selectOne(templateQueryWrapper);
        if (ObjectUtil.isNull(templateDo)) {
            throw new BusinessException("查询小程序订阅消息模板异常 配置不存在 templateId:" + code);
        }
        return BeanUtil.convertBean(templateDo, WxMaMsgTemplateVO.class);
    }

    @SneakyThrows
    @Override
    public List<TemplateInfo> queryMsgTemplateListFromWx() {
        Long tenantId = UserUtils.getTenantID();
        WxMaService wxMaService = wxOpenServiceImpl.getWxOpenMaService(tenantId);
        if (wxMaService == null) {
            throw new BusinessException("无法获取小程序信息，请检查是否绑定小程序！");
        }
        WxMaSubscribeService wxMaSubscribeService = wxMaService.getSubscribeService();
        if (wxMaSubscribeService == null) {
            throw new BusinessException("无法获取小程序信息，请检查是否绑定小程序！");
        }
        List<TemplateInfo> templateList = wxMaSubscribeService.getTemplateList();
        return templateList;
    }

    private WxMaMsgTemplateServiceImpl getBean() {
        return SpringBeanUtil.getBean(WxMaMsgTemplateServiceImpl.class);
    }

}
